<script setup>
import GoodsList from '@/components/goods/GoodsList.vue'
import PlanInfo from '../inplanGoods/components/PlanInfo.vue'
import { outplanGoodsListApi, outplanGoodsDeleteApi } from '@/apis/reservation.js'
import { ref } from 'vue'
import { onLoad, onReachBottom, onShow } from '@dcloudio/uni-app'
import MoreBtn from '@/components/MoreBtn.vue'
import { importDataUrl } from '@/common/config.js'
import { getToken } from '@/utils/index.js'

const params = ref({
  pageSize: 10,
  pageNum: 1,
  planid: "",
  planname: ""
})
const planObj = ref({})
onLoad(option => {
  console.log("12321")
  const data = JSON.parse(option.data)
  planObj.value = data
  params.value.planid = data.id
  params.value.planname = data.planname
})
onShow(() => {
  init()
  if (params.value.planid) {
    getAlertList()
  }
})
const loadStatus = ref({
  status: "loadmore", // loadmore, loading, nomore
  noMore: false,
  loading: false
})
const init = () => {
  params.value.pageNum = 1
  loadStatus.value.status = 'loadmore'
  loadStatus.value.noMore = false
  loadStatus.value.loading = false
}

const goodsList = ref([])
const getAlertList = async () => {
  // 防止重复加载
  if (loadStatus.value.noMore || loadStatus.value.loading) return
  loadStatus.value.loading = true
  loadStatus.value.status = "loading"
  try {
    const res = await outplanGoodsListApi(params.value)
    const { rows, total } = res
    // 如果是第一页，重置数据
    if (params.value.pageNum === 1) {
      goodsList.value = rows
    } else {
      goodsList.value = [...goodsList.value, ...rows]
    }
    // 判断是否还有更多数据
    if (rows.length < params.value.pageSize || goodsList.value.length >= total) {
      loadStatus.value.noMore = true
      loadStatus.value.status = "nomore"
    } else {
      loadStatus.value.status = "loadmore"
    }
    // 只有成功获取数据后才增加页码
    params.value.pageNum++
  } catch {
    // 失败时恢复状态
    loadStatus.value.status = "loadmore"
  } finally {
    loadStatus.value.loading = false
  }
}
onReachBottom(() => {
  if (!loadStatus.value.noMore) {
    getAlertList()
  }
})

const handlerDelete = item => {
  uni.showModal({
    title: '温馨提示',
    content: `确定要删除${item.goodsname}的数据吗?`,
    success: async res => {
      if (!res.confirm) return
      await outplanGoodsDeleteApi(item.id)
      goodsList.value = goodsList.value.filter(i => i.id !== item.id)
    }
  })
}
const handlerEdit = (item) => {
  const { planid, planname } = params.value
  uni.navigateTo({
    url: `/pages/reservation/outplanGoods/form?planid=${planid}&planname=${planname}&id=${item.id}`
  })
}

const handlerInplanGoodsForm = () => {
  const { planid, planname } = params.value
  uni.navigateTo({
    url: `/pages/reservation/outplanGoods/form?planid=${planid}&planname=${planname}`
  })
}

const handlerInplanData = () => {
  // 统一上传方法
  const uploadFile = (filePath) => {
    const { planid } = params.value
    uni.uploadFile({
      url: importDataUrl(`logistics/ingoods/importData?planid=${planid}`),
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': 'Bearer ' + getToken()
      },
      success(data) {
        try {
          const res = JSON.parse(data.data)
          uni.$u.toast(res.msg || '导入成功')
          setTimeout(() => {
            init()
            getAlertList()
          }, 100)
        } catch (e) {
          uni.$u.toast("导入结果解析失败")
        }
      },
      fail(e) {
        uni.$u.toast("导入失败")
      }
    })
  }

  // APP端 - 
  //#ifdef APP-PLUS
  const plugin = uni.requireNativePlugin('GW-ChooseFileModule')
	plugin.chooseFile({
		  count:1,
		extension: ["xls", "xlsx"],
	},res => {
		if(res.state != 200) return uni.$u.toast('上传失败')
		uploadFile(res.files[0].path)
	})
  //#endif

  // 微信小程序
  //#ifdef MP-WEIXIN
  uni.chooseMessageFile({
    count: 1,
    type: 'file',
    extension: ['.xlsx', '.xls'],
    success: (res) => {
      uploadFile(res.tempFiles[0].path)
    },
    fail: () => {
      uni.$u.toast('选择文件失败')
    }
  })
  //#endif
}
</script>

<template>
	<view class="page_container">
	  <u-sticky>
		<PlanInfo :planInfo="planObj" />
	  </u-sticky>
	  <GoodsList :goodsList="goodsList" :loadmoreStatus="loadStatus.status" @clickDelete="handlerDelete"
		@clickEdit="handlerEdit" />
	</view>
  <MoreBtn>
    <view class="more_list flex_fd">
      <view class="flex" @click="handlerInplanGoodsForm">添加货物</view>
      <view class="flex" @click="handlerInplanData">导入数据</view>
    </view>
  </MoreBtn>
</template>

<style lang="scss" scoped>
.more_list {
  width: 170rpx;
  padding-top: 30rpx;

  view {
    padding-bottom: 30rpx;
  }
}
</style>
